#!/usr/bin/env python
# -*- coding:utf-8 -*-

import sys
import pprint
import urllib
import urllib2


def getpath():
    pprint.pprint(sys.path)


# read(),readline(),readlines(),fileno(),close()：都与文件操作一样，这里不再赘述。可以参考前面有关文件章节
# info()：返回头信息
# getcode()：返回http状态码
# geturl()：返回url
def urllibt():
    itdiffer = urllib.urlopen("http://www.baidu.com")
    print itdiffer.read()
    print itdiffer.info()
    print itdiffer.geturl()
    print itdiffer.getcode()


def go(a, b, c):
    per = 100.0 * a * b / c
    if per > 100:
        per = 100
    print "%.2f%%" % per


def retrive():
    url = "https://oimagea2.ydstatic.com/image?id=-8567581434200966859&product=dict&_w=350&_h=200&originWidth=350&originHeight=200"
    local = "g.jpg"
    urllib.urlretrieve(url, local, go)


def request01():
    req = urllib2.Request("http://www.itdiffer.com")
    response = urllib2.urlopen(req)
    page = response.read()
    print page


def requestpost():
    url = 'http://www.itdiffer.com/register.py'
    values = {'name': 'qiwsir',
              'location': 'China',
              'language': 'Python'}

    data = urllib.urlencode(values)  # 编码
    req = urllib2.Request(url, data)  # 发送请求同时传data表单
    response = urllib2.urlopen(req)  # 接受反馈的信息
    the_page = response.read()  # 读取反馈的内容
    print the_page


def requestheader():
    url = 'http://www.itdiffer.com/register.py'
    values = {'name': 'qiwsir',
              'location': 'China',
              'language': 'Python'}

    data = urllib.urlencode(values)  # 编码
    user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
    headers = {'User-Agent': user_agent}
    req = urllib2.Request(url, data, headers)
    response = urllib2.urlopen(req)


if __name__ == '__main__':
    getpath()
    print "==============================="
    urllibt()
    print "==============================="
    retrive()
